<script lang="ts" setup>
  import type {
    CmsExam,
    CmsExamQuestion,
    CmsExamQuestionChoice,
  } from '@/types/cms';
  import { onMounted, ref } from 'vue';
  import _ from 'lodash';
  import { Form, Message } from '@arco-design/web-vue';
  import {
    createExam,
    getExamDetail,
    updateExam,
    updateQuestion,
    getQuestion,
  } from '@/api/cms';
  import ExamQuestion from './question.vue';

  const props = defineProps<{
    articleId: string;
  }>();

  const emit = defineEmits(['close']);

  const data = ref<Partial<CmsExam>>({});
  const initData = async () => {
    const examRes = await getExamDetail(props.articleId);
    if (examRes.data.data) {
      data.value = examRes.data.data;
      const questionRes = await getQuestion(data.value.id as string);
      if (questionRes.data.data) {
        questionRes.data.data.forEach((q) => {
          q.choices = JSON.parse(
            q.questionChoice || '[]'
          ) as CmsExamQuestionChoice[];
        });
        data.value.questions = questionRes.data.data;
      }
    }
  };

  const handleDownQuestion = (index: number) => {
    if (data.value.questions) {
      if (index === data.value.questions.length - 1) return;

      const questions = _.cloneDeep(data.value.questions);
      const q = questions.splice(index, 1)[0];
      questions.splice(index + 1, 0, q);
      data.value.questions = [];
      setTimeout(() => {
        data.value.questions = questions;
      }, 0);
    }
  };

  const handleUpQuestion = (index: number) => {
    if (index === 0) return;

    if (data.value.questions) {
      const questions = _.cloneDeep(data.value.questions);
      const q = questions.splice(index, 1)[0];
      questions.splice(index - 1, 0, q);
      data.value.questions = [];
      setTimeout(() => {
        data.value.questions = questions;
      }, 0);
    }
  };

  const handleRemoveQuestion = (index: number) => {
    if (data.value.questions) {
      data.value.questions?.splice(index, 1);
    }
  };

  onMounted(() => {
    initData();
  });

  const handleAddQuestion = () => {
    if (!data.value.questions) {
      data.value.questions = [];
    }
    data.value.questions.push({
      choices: [{}, {}, {}, {}],
    });
  };

  const handleQuestionUpdated = (
    q: Partial<CmsExamQuestion>,
    e: Partial<CmsExamQuestion>
  ) => {
    _.assign(q, e);
  };

  const formRef = ref<InstanceType<typeof Form> | null>(null);
  const saving = ref(false);

  const handleSubmit = async () => {
    if (formRef.value) {
      const validate = await formRef.value.validate();
      if (!validate) {
        const exam = {
          ...data.value,
        };
        if (!exam.questions || exam.questions.length === 0) {
          Message.warning('请至少添加一个问题');
          return;
        }

        for (let i = 0; i < exam.questions.length; i += 1) {
          const question = exam.questions[i];
          if (!question.choices || question.choices.length <= 1) {
            Message.warning(`请为${question.title}设置答案`);
            return;
          }
          question.questionChoice = JSON.stringify(question.choices);
        }

        saving.value = true;
        try {
          exam.articleId = props.articleId;
          const examRes = exam.id
            ? await updateExam(exam)
            : await createExam(exam);
          exam.questions.forEach((q, index) => {
            q.examId = examRes.data.data.id;
            q.sortNum = 1000000 - index;
          });

          await updateQuestion(exam.questions);
          Message.success('问卷设置成功');
          emit('close');
        } finally {
          saving.value = false;
        }
      }
    }
  };
</script>

<template>
  <a-drawer title="答题加积分" :width="700" visible @before-ok="handleSubmit">
    <a-form ref="formRef" :model="data" layout="vertical">
      <a-form-item
        label="试卷名称"
        field="title"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-input v-model="data.title" />
      </a-form-item>
      <a-row :gutter="10">
        <a-col :span="8">
          <a-form-item
            label="全部答对积分"
            field="coinPointCount"
            :rules="[{ required: true, message: '不能为空' }]"
          >
            <a-input-number
              v-model="data.coinPointCount"
              hide-button
              :precision="0"
              :min="0"
              :step="1"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="答对80%积分"
            field="eightCoinPointCount"
            :rules="[{ required: true, message: '不能为空' }]"
          >
            <a-input-number
              v-model="data.eightCoinPointCount"
              hide-button
              :precision="0"
              :min="0"
              :step="1"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            label="答对60%积分"
            field="passCoinPointCount"
            :rules="[{ required: true, message: '不能为空' }]"
          >
            <a-input-number
              v-model="data.passCoinPointCount"
              hide-button
              :precision="0"
              :min="0"
              :step="1"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <exam-question
        v-for="(question, index) in data.questions || []"
        :key="index"
        :question="question"
        :index="index"
        @down="handleDownQuestion(index)"
        @up="handleUpQuestion(index)"
        @remove="handleRemoveQuestion(index)"
        @change="handleQuestionUpdated(question, $event)"
      />
    </a-form>
    <div class="add" @click="handleAddQuestion"> <icon-plus />添加题目 </div>
  </a-drawer>
</template>

<style lang="less" scoped>
  .add {
    line-height: 32px;
    border: 1px dashed var(--color-border-3);
    border-radius: 4px;
    text-align: center;
    color: var(--color-text-3);
    cursor: pointer;
    &:hover {
      border-color: rgb(var(--primary-6));
      color: rgb(var(--primary-6));
    }
  }
</style>
